package com.ws.control;

import com.alibaba.fastjson.JSON;
import com.ws.entity.SssfmNxYthServer;
import com.ws.utils.InitKeyHttpUtil;
import com.ws.utils.safeUtil.TranSM4Utils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName YthController
 * @Description TODO
 * @Author zhengchenggong
 * @Date 2020/12/8 10:39 上午
 * @Version 1.0
 **/
@RestController
@RequestMapping("/nxYthController")
public class YthController {

    @RequestMapping("/sendPayNotice")
    public String sendPayNotice(HttpServletRequest request, HttpServletResponse response, @RequestBody String req){
        System.out.println("---进入SssfmNxYthServiceImpl.sendPayNotice---");
        System.out.println("解密前报文：" + req);
        String sm4Key = this.getServerTempKey(request);
        System.out.println("sm4临时秘钥："+sm4Key);

        String jiem = TranSM4Utils.decryptData_CBC(req, sm4Key.substring(0, 16), sm4Key.substring(16));
        System.out.println("解密后报文："+jiem);

        Map map = new HashMap<>();
        map.put("result","0");
        map.put("message","测试接收成功");
        System.out.println("加密前返回："+JSON.toJSONString(map));
        String res = TranSM4Utils.encryptData_CBC(JSON.toJSONString(map), sm4Key.substring(0, 16), sm4Key.substring(16));
        System.out.println("加密后返回："+res);
        return res;

    }

    //用长秘钥解析报文头得临时秘钥
    private String getServerTempKey(HttpServletRequest request) {
        String tempKey = null;
        try {
            String se_tempKey = request.getHeader("SE_tempKey");
            System.out.println("请求方SE_tempKey=="+se_tempKey);
            SssfmNxYthServer sssfmNxYthServer = InitKeyHttpUtil.getServerByDisCodeAndMethod("pub", "applyTempKey");
            System.out.println("长秘钥：" + sssfmNxYthServer.getLongKey());
            tempKey = TranSM4Utils.decryptData_CBC(se_tempKey, sssfmNxYthServer.getLongKey().substring(0, 16), sssfmNxYthServer.getLongKey().substring(16));
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("解析请求方临时秘钥失败");
        }
        return tempKey;
    }

}
